package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.service.UserService;
import com.sun.deploy.ui.DialogTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 支付订单,用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("支付订单的信息: {}", orders.toString());

        ordersService.submit(orders);

        return R.success("用户下单成功");
    }

    /**
     * 用户再来一单
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        log.info("再来一单的订单id: {}",orders.getId());

        Long ordersId = orders.getId();

        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(ordersId!=null,OrderDetail::getOrderId,ordersId);

        List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);

        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            //shoppingCart.setName(item.getName());
            //shoppingCart.setImage(item.getImage());
            //shoppingCart.setDishId(item.getDishId());
            //shoppingCart.setSetmealId(item.getSetmealId());
            //shoppingCart.setDishFlavor(item.getDishFlavor());
            //shoppingCart.setNumber(item.getNumber());
            BeanUtils.copyProperties(item,shoppingCart);

            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("添加购物车成功");
    }

    /**
     * 移动端订单分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {
        log.info("查询订单->page: {}, pageSize: {}", page, pageSize);

        //获取用户id
        Long userId = BaseContext.getCurrentId();

        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();

        //创建Orders构造器
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(userId != null, Orders::getUserId, userId);
        ordersLambdaQueryWrapper.orderByDesc(Orders::getCheckoutTime);
        //分页查询
        ordersService.page(ordersPage, ordersLambdaQueryWrapper);

        //拷贝对象
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");

        //获取ordersPage的records属性
        List<Orders> ordersList = ordersPage.getRecords();

        //遍历ordersList
        List<OrdersDto> ordersDtoList = ordersList.stream().map((item) -> {

            OrdersDto ordersDto = new OrdersDto();

            //拷贝对象
            BeanUtils.copyProperties(item, ordersDto);

            //查询订单里的菜品
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, item.getId());

            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);

            //赋值
            ordersDto.setOrderDetails(orderDetailList);

            //获取单个订单的菜品总数
            Integer sumNum = 0;

            for (OrderDetail orderDetail : orderDetailList) {
                Integer number = orderDetail.getNumber();
                sumNum += number;
            }

            //赋值
            ordersDto.setSumMum(sumNum);

            return ordersDto;
        }).collect(Collectors.toList());

        //赋值
        ordersDtoPage.setRecords(ordersDtoList);

        return R.success(ordersDtoPage);
    }

    /**
     * 客户端订单的分页查询
     *
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime) {
        //@DateTimeFormat( pattern = "yyyyMMddHHmmss")
        log.info("page: {}, pageSize: {}, number: {}, beginTime: {}, endTime: {}", page, pageSize, number, beginTime, endTime);

        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();

        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();

        ordersLambdaQueryWrapper.like(number != null, Orders::getNumber, number);

        if (beginTime != null && endTime != null) {
            ordersLambdaQueryWrapper.between(Orders::getOrderTime, beginTime, endTime);
        }

        ordersLambdaQueryWrapper.orderByAsc(Orders::getOrderTime);

        ordersService.page(ordersPage, ordersLambdaQueryWrapper);

        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");

        List<Orders> ordersList = ordersPage.getRecords();

        List<OrdersDto> ordersDtoList = ordersList.stream().map((item) -> {

            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);

            User user = userService.getById(item.getUserId());

            String userName = user.getName();
            ordersDto.setUserName(userName);


            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);

        return R.success(ordersDtoPage);
    }

    /**
     * 客户端更改订单状态
     *
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders orders) {
        log.info("修改订单数据: {}", orders);

        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(orders.getId() != null, Orders::getId, orders.getId());
        updateWrapper.set(orders.getStatus() != null, Orders::getStatus, orders.getStatus());

        ordersService.update(updateWrapper);


        return R.success("修改成功");
    }
}
